物件 & 類別
相依關係
Object and Class
class UserAccount { private int balance = 0; // 帳戶餘額,初始為0 // 清空帳戶餘額 public void clearAccount() { balance = 0; } // 存款 public void deposit(int amount) { balance += amount; // balance = balance + amount } // 查詢目前餘額 public int getBalance() { return balance; } } public class Person { public static void main(String[] args) { // 建立兩個帳戶 UserAccount apple = new UserAccount(); UserAccount android = new UserAccount(); // 操作帳戶 apple.deposit(1500); android.deposit(2200); // 顯示帳戶餘額 System.out.println("Apple has " + apple.getBalance() + " dollars."); System.out.println("Android has " + android.getBalance() + " dollars."); } }